package com.example.myapp.Activity;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.myapp.Listviewloading.ChatHeaderAdapter;
import com.example.myapp.Model.Msg;
import com.example.myapp.Model.MyData;
import com.example.myapp.Model.User;
import com.example.myapp.R;
import com.example.myapp.ADO.VolleyChatAdapter;
import com.sak.ultilviewlib.UltimateRefreshView;
import com.sak.ultilviewlib.interfaces.OnHeaderRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.QueryListener;

public class VolleyChat extends AppCompatActivity {
    private List<Msg> msgList = new ArrayList<>();
    private EditText inputMsg;
    private TextView send;
    private String Userid;
    private String iconUrl;
    private String userName;
    private Timer timer;
    private ImageView msg_chatmeun;
    private int sumchat;
    private String chatkey ;
    private String chatkey2 ;
    private MyData myData;

    private LinearLayoutManager layoutManager = new LinearLayoutManager(VolleyChat.this);
    private RecyclerView msgRecyclerView;
    private VolleyChatAdapter adapter;
    private UltimateRefreshView mUltimateRefreshView;
    private int page = 0;
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
    private String updatatime="";
    private Boolean shenfen=false;
    private String url1 ="http://pybchat.justwen233.cn/findMyChatMsg";//查找所有聊天记录
    private String url2 ="http://pybchat.justwen233.cn/addChatMsg";//添加聊天记录
    private String url3 ="http://pybchat.justwen233.cn/findLateTimeMyChatMsg";//查找最新聊天记录
    private String url4 ="http://pybchat.justwen233.cn/updateReceiptgCount";//更新聊天记录条数（阅读未接收数据）
    private String url5 ="http://pybchat.justwen233.cn/addUser";//添加用户信息
    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 0:
                    //查找Person表里面id为6b6c11c537的数据
                    BmobQuery<User> bmobQuery = new BmobQuery<User>();
                    bmobQuery.getObject(Userid, new QueryListener<User>() {
                        @Override
                        public void done(User object,BmobException e) {
                            if(e==null){
                                Log.w("aaa","查询成功");
//                                shenfen= object.getBusiness();
//                                Toast.makeText(getApplicationContext(),"身份"+object.getBusiness(),Toast.LENGTH_SHORT).show();
                            }else{
                                Log.w("aa","查询失败：" + e.getMessage());
                            }
                        }
                    });
                    queryALLMsgs(iconUrl);
                    break;
                case 1:
                addMsg(Userid,inputMsg.getText().toString());
                    break;
                case 2:

                    Map<String, String> map=new HashMap<String, String>();
                    map.put("author", BmobUser.getCurrentUser(User.class).getObjectId());
                    map.put("other", Userid);
                    map.put("latetime", updatatime);
                    JSONObject params=new JSONObject(map);
                    RequestQueue requestQueue3 = Volley.newRequestQueue(VolleyChat.this);
                    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url3, params, new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                JSONArray jsonArray= response.getJSONArray("result");
                                Log.w("vivi", "onResponse: "+ response);
                                if(jsonArray.length()>0){
                                    List<Msg> msgs= JSONArrayToArrayList(jsonArray);
                                    updatatime=msgs.get(0).getCreatedAt();
                                    Collections.reverse(msgs);

                                    for (int j =0;j<msgs.size();j++){
                                        msgList.add(msgs.get(j));
                                        adapter.notifyItemInserted(msgList.size()-1);
                                        msgRecyclerView.scrollToPosition(msgList.size()-1);
                                    }
                                }
                            }catch (JSONException e ){
                                Log.w("vivi", "onResponse: "+ e.getMessage());
                            }

                        }
                    }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            error.printStackTrace();
                            Log.d("vivi", "error: " + error.getMessage());
                        }
                    });
                    //添加队列
                    requestQueue3.add(jsonObjectRequest);
                    requestQueue3.cancelAll(this);
                    break;
                case 3:
                    adduser(myData.getObjID(),myData.getUserName(),myData.getDfIconpath());
                    adduser(Userid,userName,iconUrl);
                    break;

            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        inputMsg =  findViewById(R.id.input_msg);
        send =findViewById(R.id.send);
        msg_chatmeun=findViewById(R.id.msg_chatmeun);

        ImageView msg_back = findViewById(R.id.msg_back);
        TextView msg_username = findViewById(R.id.msg_username);
        msgRecyclerView =  findViewById(R.id.msg_recycler_view);
        mUltimateRefreshView = (UltimateRefreshView)findViewById(R.id.refreshView);
        mUltimateRefreshView.setBaseHeaderAdapter(new ChatHeaderAdapter(VolleyChat.this));
        /**头部下拉刷新事件*/
        mUltimateRefreshView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {
            @Override
            public void onHeaderRefresh(UltimateRefreshView view) {
                /**
                 * 某个时间后
                 */
                page++;
                int offset= page*10;
                Map<String, String> map=new HashMap<String, String>();
                map.put("author", BmobUser.getCurrentUser(User.class).getObjectId());
                map.put("other",Userid);
                map.put("offset", ""+offset);
                map.put("limit", "10");
                JSONObject params=new JSONObject(map);
                RequestQueue requestQueue2 = Volley.newRequestQueue(VolleyChat.this);
                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url1, params, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            JSONArray jsonArray= response.getJSONArray("result");
                          List<Msg> msgs=JSONArrayToArrayList(jsonArray);
                            Collections.reverse(msgList);
                              msgList.addAll(msgs);
                            Collections.reverse(msgList);
                             adapter.notifyDataSetChanged();
                            Log.w("vivi", "onResponse: "+ response);
                        }catch (JSONException e ){
                            Log.w("vivi", "onResponse: "+ e.getMessage());
                        }
                        mUltimateRefreshView.onHeaderRefreshComplete();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        Log.d("vivi", "error: " + error.getMessage());

                        mUltimateRefreshView.onHeaderRefreshComplete();
                    }
                });
                //添加队列
                requestQueue2.add(jsonObjectRequest);
                requestQueue2.cancelAll(this);


            }
        });
        msg_username.setText(userName);
        myData = (MyData) getApplication();
        Intent intent =getIntent();
        Userid =intent.getStringExtra("userID");
        iconUrl =intent.getStringExtra("iconUrl");
        userName=intent.getStringExtra("userName");
        msg_username.setText(userName);
        chatkey=myData.getObjID()+Userid;
        chatkey2=Userid+myData.getObjID();
        //  Log.w("aaaa", "聊天秘钥:"+ chatkey);

        Message message=new Message();
        message.what=0;
        handler.sendMessage(message);

        Message message2=new Message();
        message2.what=3;
        handler.sendMessage(message2);

        msg_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (timer!=null){
                    timer.cancel();
                }
                readMsg();
                finish();
            }
        });
        TextWatcher watcher =new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (inputMsg.getText().toString().trim().length()>0){
                    send.setBackground(getDrawable(R.drawable.btnsend));
                }
                else {
                    send.setBackground(getDrawable(R.drawable.msg_btn));

                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };
        inputMsg.addTextChangedListener(watcher);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = inputMsg.getText().toString();
                if (!"".equals(content)) {
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            }
        });
        msg_chatmeun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//                    Intent intent = new Intent(VolleyChat.this, Friendshome.class);
//                    intent.putExtra("objId",Userid);


                Intent intent = new Intent(VolleyChat.this, Friendshome.class);
                intent.putExtra("userID", Userid);
                intent.putExtra("iconUrl",iconUrl);
                intent.putExtra("userName",userName);
                    startActivity(intent);

            }
        });


        // TODO 设置定时器
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {

                Message message = new Message();
                message.what = 2;
                handler.sendMessage(message);

            }
        }, 500, 2000);  // TODO 每隔一秒执行一下



    }

    /** 阅读聊天*/
    private  void readMsg(){
        Map<String, String> map2=new HashMap<String, String>();
        map2.put("author", BmobUser.getCurrentUser(User.class).getObjectId());
        map2.put("other", Userid);
        JSONObject params=new JSONObject(map2);
        RequestQueue requestQueue2 = Volley.newRequestQueue(VolleyChat.this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url4, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    Log.w("vivi", "onResponse: "+ response.toString());

                }catch (Exception e ){
                    Log.w("vivi", "onResponse: "+ e.getMessage());

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("vivi", "error: " + error.getMessage());

            }
        });
        //添加队列
        requestQueue2.add(jsonObjectRequest);
        requestQueue2.cancelAll(this);
    }
    /** 创建聊天记录统计*/
    private  void  addMsg(String otherid, String content){
        Map<String, String> map=new HashMap<String, String>();
        map.put("author", BmobUser.getCurrentUser(User.class).getObjectId());
        map.put("other", otherid);
        map.put("content", content);
        JSONObject params=new JSONObject(map);
        RequestQueue requestQueue3 = Volley.newRequestQueue(VolleyChat.this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url2, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONObject jsonObject= response.getJSONObject("result");
                    Msg msg1=new Msg();
                    msg1.setContent(jsonObject.getString("content"));
                    msg1.setAuthor(jsonObject.getString("author"));
                    msg1.setOther(jsonObject.getString("other"));
                    msg1.setCreatedAt(jsonObject.getString("createdAt"));
                    updatatime=jsonObject.getString("createdAt");
                    msgList.add(msg1);
                    if(msgList.size()==1){
                        inputMsg.setText("");
                        msgRecyclerView.setLayoutManager(layoutManager);
                        adapter = new VolleyChatAdapter(msgList,iconUrl);
                        msgRecyclerView.setAdapter(adapter);
                        msgRecyclerView.scrollToPosition(msgList.size()-1);
                    }else {
                        adapter.notifyItemInserted(msgList.size()-1);
                        msgRecyclerView.scrollToPosition(msgList.size()-1);
                        inputMsg.setText("");
                    }
                }catch (JSONException e ){
                    Log.d("vivi", "error: " + e.getMessage());
                }
                mUltimateRefreshView.onHeaderRefreshComplete();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("vivi", "error: " + error.getMessage());
                mUltimateRefreshView.onHeaderRefreshComplete();
            }
        });
        //添加队列
        requestQueue3.add(jsonObjectRequest);
        requestQueue3.cancelAll(this);


    }

    /** 获取聊天记录*/
    private  void queryALLMsgs(String otherIconUrl){
        if (!BmobUser.isLogin()) {
            Log.w("aaaa", "登陆后在操作" );
            return;
        }
        Map<String, String> map=new HashMap<String, String>();
        map.put("author", BmobUser.getCurrentUser(User.class).getObjectId());
        map.put("other",Userid);
        map.put("limit", "10");
        JSONObject params=new JSONObject(map);
        RequestQueue requestQueue = Volley.newRequestQueue(VolleyChat.this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url1, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray= response.getJSONArray("result");
                      msgList=JSONArrayToArrayList(jsonArray);
                      if(msgList.size()>0){
                          updatatime=msgList.get(0).getCreatedAt();
                      }
                    Collections.reverse(msgList);
                    msgRecyclerView.setLayoutManager(layoutManager);
                    adapter = new VolleyChatAdapter(msgList,otherIconUrl);
                    msgRecyclerView.setAdapter(adapter);
                    msgRecyclerView.scrollToPosition(msgList.size()-1);

                    Log.w("vivi", "onResponse: "+ response);
                }catch (JSONException e ){
                    Log.w("vivi", "onResponse: "+ e.getMessage());
                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("vivi", "error: " + error.getMessage());

            }
        });
        //添加队列
        requestQueue.add(jsonObjectRequest);
        requestQueue.cancelAll(this);

    }


    private List<Msg> JSONArrayToArrayList(JSONArray jsonArray){
        List<Msg> msgList=new ArrayList<>();
        try {
            for (int i=0;i<jsonArray.length();i++){
                JSONObject jsonObject  = jsonArray.getJSONObject(i);
                Msg msg=new Msg();
                msg.setAuthor(jsonObject.getString("author"));
                msg.setOther(jsonObject.getString("other"));
                msg.setChatkey(jsonObject.getString("Chatkey"));
                msg.setContent(jsonObject.getString("content"));
                msg.setShow(jsonObject.getInt("show"));
                msg.setCreatedAt(jsonObject.getString("createdAt"));
                msgList.add(msg);
            }
        }catch (Exception e ){

        }



        return msgList;
    }
    private void adduser(String userid, String userName, String iconUrl){
        Map<String, String> map2=new HashMap<String, String>();
        map2.put("objectId",userid);
        map2.put("username", userName);
        map2.put("icon", iconUrl);

        JSONObject params=new JSONObject(map2);
        RequestQueue requestQueue2 = Volley.newRequestQueue(VolleyChat.this);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url5, params, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    Log.w("vivi", "onResponse: "+ response.toString());

                }catch (Exception e ){
                    Log.w("vivi", "onResponse: "+ e.getMessage());

                }

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                Log.d("vivi", "error: " + error.getMessage());

            }
        });
        //添加队列
        requestQueue2.add(jsonObjectRequest);

    }
    public void onBackPressed() {
        if (timer!=null){
            timer.cancel();
        }
        readMsg();
        finish();
    }
}
